package com.lmk.ms.common.net.tcp.client.service.impl;

import com.lmk.ms.common.net.tcp.client.service.TcpClientService;
import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 简单的TCP客户端业务服务适配器
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public abstract class TcpClientServiceAdapter implements TcpClientService {
    @Override
    public Object handel(Socket socket) {
        Object result = null;
        if(socket == null) {
            log.error("业务处理失败，socket不可为空！");
            return null;
        }

        log.debug("业务开始");
        try(
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream())
        ) {
            result = run(in, out); // 调用子类实现的方法
        } catch (Exception e) {
            log.error("业务异常：", e);
        } finally {
            log.debug("业务结束");
        }
        return result;
    }

    /**
     * 子类重写该方法时，不要处理IO异常
     * @param in
     * @param out
     * @throws IOException
     */
    public abstract Object run(DataInputStream in, DataOutputStream out) throws IOException;

}
